// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { _id, userInfo, ...data } = event

  let status = 0
  if (data.sn) {
    const res = await axios
      .get('http://124.70.50.10:33333/sendMsg', {
        params: { sn: data.sn, msg: 'cast' },
      })
      .then(resp => resp.data)
    if (res.error === 0) {
      status = 1
    }
  }

  if (!_id) {
    await db.collection('screen').add({
      data: {
        _id,
        castPeriods: [['7:00', '22:00']],
        price: 100,
        createAt: new Date(),
        status,
        ...data,
      },
    })
  } else {
    await db
      .collection('screen')
      .where({ _id })
      .update({
        data: {
          ...data,
          status,
        },
      })
  }
}
